if not HST then return end

local L = HST.L

-- EW means Expose Weakness, is set bonus for 8 pieces of hunter tier 2 armor set.
HST.EWName = L["Expose Weakness"]
HST.EWBattleStart = nil
HST.EWBattlePersist = 0
HST.EWTriggered = nil
HST.EWAccumlated = 0

function HST:HandleEWTriggered()
    HST.EWTriggered = GetTime()
end

function HST:HandleEWVanished()
    if self.EWTriggered then
        -- Judgement of this flag because it may be
        -- called when leaving the battle.
        self.EWAccumlated = self.EWAccumlated + (GetTime() - self.EWTriggered)
    end
    
    self.EWTriggered = nil
end

function HST:EWHandleTargetAuraChanged()
    if not self.EWBattleStart then return end

    if not self.EWTriggered and self:TargetHasDebuff(self.EWName) then
        self:HandleEWTriggered()
    elseif self:TargetNoDebuff(self.EWName) then
        self:HandleEWVanished()
    end
end

function HST:EWHandleEnterBattle()
    if self.EWBattleStart then return end

    self:EWCleanCache()
    self.EWBattleStart = GetTime()
end

function HST:EWHandleLeaveBattle()
    if not self.EWBattleStart then return end 
    
    self:HandleEWVanished()
    self.EWBattlePersist = GetTime() - self.EWBattleStart
    self:EWReportCoverage()
    self:EWCleanCache()
end

function HST:EWReportCoverage()
    local c = self.EWAccumlated / self.EWBattlePersist
    c = c - math.mod(c, 0.001)
    local message = L["Battle Duration"] .. ": " ..
        tostring(self:ModuleTime(self.EWBattlePersist)) .. "s, " ..
        L["EW Duration"] .. ": " .. tostring(self:ModuleTime(self.EWAccumlated)) .. "s, " ..
        L["EW Coverage"] .. ": " .. tostring(c * 100) .. "%"
    SendChatMessage(message, "WHISPER", nil, GetUnitName("player"))
end

function HST:ModuleTime(time)
    local t = time
    return t - math.mod(t, 0.01)
end

function HST:EWCleanCache()
    self.EWBattleStart = nil
    self.EWBattlePersist = 0
    self.EWTriggered = nil
    self.EWAccumlated = 0
end

function HST:EWCoverageEnabled()
    return HST.db.profile.ew
end

function HST:OnEWToggle(current)
    HST.db.profile.ew = not current

    if not HST.db.profile.ew then
        self:EWCleanCache()
    end
end